import React, { useState, useEffect } from 'react';
import { ShopOutlined, FileTextOutlined, PayCircleOutlined, TeamOutlined, ClockCircleOutlined, UserOutlined, DesktopOutlined, ShoppingOutlined, CreditCardOutlined, CarOutlined, RollbackOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { Table, Button } from 'antd';
import { _apiMemberRegisterCount, _apiMemberRegisterPage,
  _apiMemberConsumeCount , _apiOrderAmountCount ,
   _apiProductSaleCount, _apiMemberRegisterview, 
   _apiOrderTotalCount, _apiRefundCount, _apiProductAudit, 
   _apiMemberAudit, _apiMerchantAudit
} from '../../../api';
import styles from './HomePage.module.css';

function HomePage() {
  // 将cards移到组件内部并使用useState管理
  const [cards, setCards] = useState([
    {
      title: '新增商户',
      value: '0',
      icon: <ShopOutlined />,
      className: styles.redCard
    },
    {
      title: '今日订单',
      value: '0',
      icon: <FileTextOutlined />,
      className: styles.orangeCard
    },
    {
      title: '今日销售',
      value: '0',
      icon: <PayCircleOutlined />,
      className: styles.blueCard
    },
    {
      title: '新增会员',
      value: '0',
      icon: <TeamOutlined />,
      className: styles.greenCard
    }
  ]);

  // 添加会员注册数量状态
  const [memberCount, setMemberCount] = useState(0);

  // 添加会员注册列表状态
  const [memberList, setMemberList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 添加会员消费总数状态
  const [consumeCount, setConsumeCount] = useState(0);

  // 添加订单金额统计状态
  const [orderAmount, setOrderAmount] = useState(0);

  // 添加订单数据状态
  const [orderData, setOrderData] = useState([]);

  // 添加商品销售统计状态
  const [productSaleData, setProductSaleData] = useState([]);

  // 添加会员注册视图状态
  const [memberRegisterData, setMemberRegisterData] = useState([]);

  // 添加待支付订单状态
  const [pendingOrders, setPendingOrders] = useState(0);

  // 添加待发货订单状态
  const [pendingShipOrders, setPendingShipOrders] = useState(0);

  // 添加退款订单状态
  const [refundOrders, setRefundOrders] = useState(0);

  // 添加待审商品状态
  const [pendingProducts, setPendingProducts] = useState(0);

  // 添加待审会员状态
  const [pendingMembers, setPendingMembers] = useState(0);

  // 添加待审商户状态
  const [pendingMerchants, setPendingMerchants] = useState(0);

  // 获取会员注册数量
  useEffect(() => {
    const fetchMemberCount = async () => {
      try {
        const response = await _apiMemberRegisterCount();
        if (response && response.data) {
          setMemberCount(response.data);
          // 更新cards数组中的员工数量
          setCards(prevCards => prevCards.map((card, index) => 
            index === 3 ? { ...card, value: response.data } : card
          ));
        }
      } catch (error) {
        console.error('获取会员注册数量失败:', error);
      }
    };

    fetchMemberCount();
  }, []);

  // 获取会员注册列表
  const fetchMemberList = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await _apiMemberRegisterPage({
        page,
        pageSize
      });
      if (response && response.data) {
        setMemberList(response.data.records);
        setPagination({
          current: page,
          pageSize,
          total: response.data.total
        });
      }
    } catch (error) {
      console.error('获取会员注册列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 在组件加载时获取数据
  useEffect(() => {
    fetchMemberList();
  }, []);

  // 处理表格分页变化
  const handleTableChange = (newPagination) => {
    fetchMemberList(newPagination.current, newPagination.pageSize);
  };

  // ECharts 配置项
  const option = {
    title: {
      text: '商品销售统计',
      left: '10px',
      top: '0px',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />销售数量: {c}'
    },
    xAxis: {
      type: 'category',
      data: productSaleData.slice(-7).map(item => item.title),
      boundaryGap: false,
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '销售数量',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '销售数量',
        type: 'line',
        data: productSaleData.slice(-7).map(item => Number(item.total) || 0),
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 2,
          color: '#339af0'
        },
        itemStyle: {
          color: '#339af0'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: '#339af0'
            }, {
              offset: 1,
              color: 'rgba(51, 154, 240, 0.1)'
            }]
          }
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '60px',
      containLabel: true
    }
  };

  // 获取会员消费总数
  useEffect(() => {
    const fetchConsumeCount = async () => {
      try {
        const response = await _apiMemberConsumeCount();
        if (response && response.data) {
          setConsumeCount(response.data);
          // 更新cards数组中的成交额
          setCards(prevCards => prevCards.map((card, index) => 
            index === 2 ? { ...card, value: response.data } : card
          ));
        }
      } catch (error) {
        console.error('获取会员消费总数失败:', error);
      }
    };

    fetchConsumeCount();
  }, []);

  // 获取订单金额统计
  useEffect(() => {
    const fetchOrderAmount = async () => {
      try {
        const response = await _apiOrderAmountCount();
        if (response && response.data) {
          setOrderData(response.data);
          
          // 获取今天的日期
          const today = new Date();
          const todayStr = `${today.getMonth() + 1}月${today.getDate()}日`;
          
          // 查找今天的数据
          const todayData = response.data.find(item => item.title === todayStr);
          
          // 更新cards数组中的今日订单数量和销售额
          setCards(prevCards => prevCards.map((card, index) => {
            if (index === 1) { // 今日订单数量
              return { ...card, value: todayData ? todayData.total : 0 };
            }
            if (index === 2) { // 今日销售额
              return { ...card, value: todayData ? todayData.amount : 0 };
            }
            return card;
          }));
        }
      } catch (error) {
        console.error('获取订单金额统计失败:', error);
      }
    };

    fetchOrderAmount();
  }, []);

  // 获取商品销售统计
  useEffect(() => {
    const fetchProductSale = async () => {
      try {
        const response = await _apiProductSaleCount();
        if (response && response.data) {
          setProductSaleData(response.data);
          // 更新option中的数据
          option.series[0].data = response.data.slice(-7).map(item => Number(item.total) || 0);
          option.xAxis.data = response.data.slice(-7).map(item => item.title || '');
        }
      } catch (error) {
        console.error('获取商品销售统计失败:', error);
      }
    };

    fetchProductSale();
  }, []);

  // 获取会员注册视图数据
  useEffect(() => {
    const fetchMemberRegisterView = async () => {
      try {
        const response = await _apiMemberRegisterview();
        if (response && response.data) {
          setMemberRegisterData(response.data);
          
          // 获取今天的日期
          const today = new Date();
          const todayStr = `${today.getMonth() + 1}月${today.getDate()}日`;
          
          // 查找今天的注册数量
          const todayData = response.data.find(item => item.title === todayStr);
          const todayCount = todayData ? todayData.count : 0;
          
          // 确保转换为字符串
          setCards(prevCards => prevCards.map((card, index) => 
            index === 3 ? { ...card, value: String(todayCount) } : card
          ));
        }
      } catch (error) {
        console.error('获取会员注册视图数据失败:', error);
      }
    };

    fetchMemberRegisterView();
  }, []);

  // 调用订单总数接口获取待支付订单数量
  useEffect(() => {
    const fetchOrderTotal = async () => {
      try {
        const response = await _apiOrderTotalCount({ Status: 1 });
        if (response && response.data) {
          setPendingOrders(response.data);
        }
      } catch (error) {
        console.error('获取待支付订单数失败:', error);
      }
    };

    fetchOrderTotal();
  }, []);

  // 调用订单总数接口获取待发货订单数量
  useEffect(() => {
    const fetchOrderTotal = async () => {
      try {
        const response = await _apiOrderTotalCount({ Status: 4 });
        if (response && response.data) {
          setPendingShipOrders(response.data);
        }
      } catch (error) {
        console.error('获取待发货订单数失败:', error);
      }
    };

    fetchOrderTotal();
  }, []);

  // 调用退款订单接口
  useEffect(() => {
    const fetchRefundCount = async () => {
      try {
        const response = await _apiRefundCount({ type: 1 });
        if (response && response.data) {
          // 如果返回的是数组，使用数组长度
          if (Array.isArray(response.data)) {
            setRefundOrders(response.data.length);
          } else if (typeof response.data === 'number') {
            // 如果返回的是数字，直接使用
            setRefundOrders(response.data);
          } else {
            // 其他情况设置为0
            setRefundOrders(0);
          }
        }
      } catch (error) {
        console.error('获取退款订单数失败:', error);
        setRefundOrders(0);
      }
    };

    fetchRefundCount();
  }, []);

  // 调用商品审核接口获取待审商品数量
  useEffect(() => {
    const fetchPendingProducts = async () => {
      try {
        const response = await _apiProductAudit({ Status: 1 });
        if (response && response.data) {
          // 如果返回的是数组，使用数组长度
          if (Array.isArray(response.data)) {
            setPendingProducts(response.data.length);
          } else if (typeof response.data === 'number') {
            // 如果返回的是数字，直接使用
            setPendingProducts(response.data);
          } else {
            // 其他情况设置为0
            setPendingProducts(0);
          }
        }
      } catch (error) {
        console.error('获取待审商品数失败:', error);
        setPendingProducts(0);
      }
    };

    fetchPendingProducts();
  }, []);

  // 调用会员审核接口获取待审会员数量
  useEffect(() => {
    const fetchPendingMembers = async () => {
      try {
        const response = await _apiMemberAudit({ Status: 1 });
        if (response && response.data) {
          // 如果返回的是数组，使用数组长度
          if (Array.isArray(response.data)) {
            setPendingMembers(response.data.length);
          } else if (typeof response.data === 'number') {
            // 如果返回的是数字，直接使用
            setPendingMembers(response.data);
          } else {
            // 其他情况设置为0
            setPendingMembers(0);
          }
        }
      } catch (error) {
        console.error('获取待审会员数失败:', error);
        setPendingMembers(0);
      }
    };

    fetchPendingMembers();
  }, []);

  // 调用商户审核接口获取待审商户数量
  useEffect(() => {
    const fetchPendingMerchants = async () => {
      try {
        const response = await _apiMerchantAudit({ Status: 1 });
        if (response && response.data) {
          let merchantCount = 0;
          // 如果返回的是数组，使用数组长度
          if (Array.isArray(response.data)) {
            merchantCount = response.data.length;
          } else if (typeof response.data === 'number') {
            // 如果返回的是数字，直接使用
            merchantCount = response.data;
          }
          
          setPendingMerchants(merchantCount);
          
          // 更新cards数组中的新增商户数量（第一个卡片）
          setCards(prevCards => prevCards.map((card, index) => 
            index === 0 ? { ...card, value: String(merchantCount) } : card
          ));
        }
      } catch (error) {
        console.error('获取待审商户数失败:', error);
        setPendingMerchants(0);
      }
    };

    fetchPendingMerchants();
  }, []);

  // 修改订单金额统计图表配置
  const orderOption = {
    title: {
      text: '订单金额统计',
      left: '20px',
        top: '0px',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />销售金额: {c}'
    },
    xAxis: {
      type: 'category',
      data: orderData.slice(-7).map(item => item.title || ''),
      boundaryGap: false,
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '销售金额',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '销售金额',
        type: 'line',
        data: orderData.slice(-7).map(item => Number(item.amount) || 0),
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 2,
          color: '#339af0'
        },
        itemStyle: {
          color: '#339af0'
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '60px',
      containLabel: true
    }
  };

  // 修改会员注册图表配置
  const memberOption = {
    title: {
      text: '会员注册情况',
     
      top: '0px',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />新增用户: {c}'
    },
    xAxis: {
      type: 'category',
      data: memberRegisterData.slice(-7).map(item => item.title || ''),
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '新增用户',
      minInterval: 1,
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '新增用户',
      type: 'bar',
      data: memberRegisterData.slice(-7).map(item => Number(item.count) || 0),
      itemStyle: {
        color: '#339af0'
      },
      barWidth: '40%'
    }],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '60px',
      containLabel: true
    }
  };

  return (
    <div>
      <div className={styles.cardContainer}>
        {cards.map((card, index) => (
          <div key={index} className={`${styles.card} ${card.className}`}>
            <div className={styles.cardTitle}>
              {card.icon}
              <span>{card.title}</span>
            </div>
            <div className={styles.cardValue}>
              {typeof card.value === 'object' ? '0' : card.value}
            </div>
          </div>
        ))}
      </div>
      <div className={styles.chartsRow}>
        <div className={styles.chartBox}>
          <ReactECharts 
            option={option} 
            style={{ height: '400px' }}
            className={styles.chart}
          />
        </div>
        <div className={styles.chartBox}>
          <div className={styles.todoBox}>
            <h2 className={styles.todoTitle}>
              <ClockCircleOutlined /> 待办事件
            </h2>
            <div className={styles.todoGrid}>
              <div className={styles.todoItem}>
                <UserOutlined className={styles.todoIcon} />
                <span>待审会员</span>
                <span className={styles.todoBadge}>{pendingMembers}</span>
              </div>
              <div className={styles.todoItem}>
                <DesktopOutlined className={styles.todoIcon} />
                <span>待审商户</span>
                <span className={styles.todoBadge}>{pendingMerchants}</span>
              </div>
              <div className={styles.todoItem}>
                <ShoppingOutlined className={styles.todoIcon} />
                <span>待审商品</span>
                <span className={styles.todoBadge}>{pendingProducts}</span>
              </div>
              <div className={styles.todoItem}>
                <CreditCardOutlined className={styles.todoIcon} />
                <span>待支付订单</span>
                <span className={styles.todoBadge}>{pendingOrders}</span>
              </div>
              <div className={styles.todoItem}>
                <CarOutlined className={styles.todoIcon} />
                <span>待发货订单</span>
                <span className={styles.todoBadge}>{pendingShipOrders}</span>
              </div>
              <div className={styles.todoItem}>
                <RollbackOutlined className={styles.todoIcon} />
                <span>待退款订单</span>
                <span className={styles.todoBadge}>{refundOrders}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className={styles.chartsRow}>
        <div className={`${styles.chartBox} ${styles.mediumChart}`}>
          <ReactECharts 
            option={orderOption} 
            style={{ height: '400px' }}
            className={styles.chart}
          />
        </div>
        <div className={`${styles.chartBox} ${styles.smallChart}`}>
          <ReactECharts 
            option={memberOption} 
            style={{ height: '400px' }}
            className={styles.chart}
          />
        </div>
      </div>
    </div>
  );
}

export default HomePage; 